import { useMemo, useState } from "react";
import { AppstoreOutlined, ReloadOutlined } from "@ant-design/icons";
import type { PaginationProps, TableColumnsType, TableProps } from "antd";
import { Button, Flex, Pagination, Popover, Table as AntTable } from "antd";
import HideColumn from "@/components/hide-column";

interface ITableProps<T> extends TableProps<T> {
  leftActions?: React.ReactNode;
  rightActions?: React.ReactNode;
  columns: TableColumnsType<T>;
  canHideColumns?: TableColumnsType<T>;
  pagination?: PaginationProps;
  onRefresh?: () => void;
  onPageChange?: (page: number, pageSize: number) => void;
}

export default function Table<T extends object>({ canHideColumns, onRefresh, ...props }: ITableProps<T>) {
  // 生成可隐藏列的选项
  const hideColumnOptions = useMemo(() => {
    return (
      canHideColumns?.map(({ key, title }) => ({
        label: (title as string) || "",
        value: key as string,
      })) || []
    );
  }, [canHideColumns]);

  // 默认显示所有可隐藏的列
  const [checkedList, setCheckedList] = useState<string[]>(hideColumnOptions.map((opt) => opt.value));

  // 根据 checkedList 过滤列
  const visibleColumns = useMemo(() => {
    if (!canHideColumns || canHideColumns.length === 0) {
      return props.columns;
    }

    // 创建可隐藏列的 key 集合
    const canHideColumnKeys = new Set(canHideColumns.map((item) => item.key));

    return props.columns.map((col) => {
      // 如果该列在可隐藏列表中，根据 checkedList 决定是否隐藏
      if (canHideColumnKeys.has(col.key)) {
        return {
          ...col,
          hidden: !checkedList.includes(col.key as string),
        };
      }
      // 否则该列始终显示
      return col;
    });
  }, [props.columns, canHideColumns, checkedList]);

  return (
    <Flex vertical gap={10} className="h-full overflow-hidden">
      <Flex className="flex-shrink-0">
        <Flex gap={8} flex={1} justify="start" key="left-actions">
          {props.leftActions}
        </Flex>
        <Flex gap={8} flex={1} justify="end" key="right-actions">
          {props.rightActions}
          {canHideColumns && canHideColumns.length > 0 && (
            <Popover
              content={
                <HideColumn options={hideColumnOptions} checkedList={checkedList} onChange={setCheckedList} />
              }
              trigger="click"
              placement="bottomRight"
            >
              <Button size="middle" type="text" icon={<AppstoreOutlined />} />
            </Popover>
          )}
          {onRefresh && <Button size="middle" type="text" icon={<ReloadOutlined />} onClick={onRefresh} />}
        </Flex>
      </Flex>
      <Flex vertical gap={10} className="w-full flex-1">
        <AntTable
          {...props}
          columns={visibleColumns}
          pagination={false}
          scroll={props.scroll || { x: 1200 }}
        />
        <Flex justify="end">
          <Pagination
            total={props.pagination?.total || 0}
            current={props.pagination?.current || 1}
            pageSize={props.pagination?.pageSize}
            showSizeChanger={props.pagination?.showSizeChanger}
            pageSizeOptions={props.pagination?.pageSizeOptions}
            onChange={(page, pageSize) => props.onPageChange?.(page, pageSize)}
          />
        </Flex>
      </Flex>
    </Flex>
  );
}
